package com.iflytek.springboot_medicine.service.impl;

import com.iflytek.springboot_medicine.entity.Medicine;
import com.iflytek.springboot_medicine.entity.Shopping;
import com.iflytek.springboot_medicine.entity.User;
import com.iflytek.springboot_medicine.pojo.OrderPojo;
import com.iflytek.springboot_medicine.pojo.ResponseMessage;
import com.iflytek.springboot_medicine.service.OrderPojoRepository;
import com.iflytek.springboot_medicine.service.ShoppingRepository;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.Date;
import java.util.List;

@Service
public class ShoppingServiceImpl {
    private final UserServiceImpl userService;
    private final MedicineServiceImpl medicineService;
    private final ShoppingRepository shoppingRepository;
    private final OrderPojoRepository orderPojoRepository;
    private static final Logger log = LoggerFactory.getLogger(ShoppingServiceImpl.class);

    public ShoppingServiceImpl(UserServiceImpl userService, MedicineServiceImpl medicineService, ShoppingRepository shoppingRepository,OrderPojoRepository orderPojoRepository) {
        this.medicineService=medicineService;
        this.userService = userService;
        this.shoppingRepository = shoppingRepository;
        this.orderPojoRepository = orderPojoRepository;
    }

    @Transactional
    public ResponseMessage<OrderPojo> addShopping(OrderPojo shopping) {
        try {
            // 1. 验证用户是否存在
            String uName = shopping.getUser_name();
            User user = userService.findByName(uName);
            if (user == null) {
                return ResponseMessage.error("用户不存在");
            }

            // 2. 验证药品是否存在并检查库存
            String meName = shopping.getName();
            Medicine medicine = medicineService.findMedicineByName(meName);
            if (medicine == null) {
                return ResponseMessage.error("药品不存在");
            }

            // 3. 检查库存是否充足
            int newStock = medicine.getStore_count() - shopping.getCount();
            if (newStock < 0) {
                return ResponseMessage.error("库存不足，无法下单");
            }

            // 4. 设置订单信息
            shopping.setCreateTime(new Date());
            shopping.setUpdateTime(new Date());
            shopping.setOrderStatus(0); // 0表示未支付状态

            // 5. 保存订单
            OrderPojo savedOrder = orderPojoRepository.save(shopping);
            if (savedOrder == null) {
                throw new RuntimeException("订单保存失败");
            }

            // 6. 更新库存
            medicine.setStore_count(newStock);
            Medicine updatedMedicine = medicineService.saveMedicine(medicine);
            if (updatedMedicine == null) {
                throw new RuntimeException("库存更新失败");
            }

            // 7. 创建购物记录
            Shopping order = new Shopping(
                medicine.getId(),
                user.getId(),
                shopping.getPrice_sum(),
                shopping.getCount()
            );
            Shopping savedShopping = shoppingRepository.save(order);
            if (savedShopping == null) {
                throw new RuntimeException("购物记录保存失败");
            }

            return ResponseMessage.success(savedOrder);
        } catch (Exception e) {
            // 记录详细错误信息
            log.error("添加购物车失败", e);
            return ResponseMessage.error("添加购物车失败: " + e.getMessage());
        }
    }

    @Transactional
    public ResponseMessage<Void> updateShopping(Integer id, int count, double priceSum) {
        try {
            // 1. 查找订单
            OrderPojo order = orderPojoRepository.findById(id)
                .orElseThrow(() -> new RuntimeException("订单不存在"));

            // 2. 验证库存
            Medicine medicine = medicineService.findMedicineByName(order.getName());
            if (medicine == null) {
                return ResponseMessage.error("药品不存在");
            }

            int stockChange = order.getCount() - count;
            int newStock = medicine.getStore_count() + stockChange;
            if (newStock < 0) {
                return ResponseMessage.error("库存不足");
            }

            // 3. 更新订单
            order.setCount(count);
            order.setPrice_sum(priceSum);
            order.setUpdateTime(new Date());
            orderPojoRepository.save(order);

            // 4. 更新库存
            medicine.setStore_count(newStock);
            medicineService.saveMedicine(medicine);

            return ResponseMessage.success();
        } catch (Exception e) {
            log.error("更新购物车失败", e);
            return ResponseMessage.error("更新购物车失败: " + e.getMessage());
        }
    }

    @Transactional
    public ResponseMessage<Void> deleteShopping(Integer id) {
        try {
            // 1. 查找订单
            OrderPojo order = orderPojoRepository.findById(id)
                .orElseThrow(() -> new RuntimeException("订单不存在"));

            // 2. 恢复库存
            Medicine medicine = medicineService.findMedicineByName(order.getName());
            if (medicine != null) {
                medicine.setStore_count(medicine.getStore_count() + order.getCount());
                medicineService.saveMedicine(medicine);
            }

            // 3. 删除订单
            orderPojoRepository.deleteById(id);

            // 4. 删除购物记录
            shoppingRepository.deleteByMedicineId(medicine.getId());

            return ResponseMessage.success();
        } catch (Exception e) {
            log.error("删除购物车失败", e);
            return ResponseMessage.error("删除购物车失败: " + e.getMessage());
        }
    }

    @Transactional
    public ResponseMessage<Void> deleteBatchShopping(List<Integer> ids) {
        try {
            for (Integer id : ids) {
                deleteShopping(id);
            }
            return ResponseMessage.success();
        } catch (Exception e) {
            log.error("批量删除购物车失败", e);
            return ResponseMessage.error("批量删除购物车失败: " + e.getMessage());
        }
    }
}
